<template>
	<view class="diet-container">
		<!-- 页面头部 -->
		<view class="page-header">
			<text class="title">饮食管理</text>
		</view>
		
		<!-- 今日饮食摘要 -->
		<view class="daily-summary">
			<view class="date-selector">
				<text class="date-label">{{ formatDate(selectedDate) }}</text>
				<view class="date-arrows">
					<text class="arrow" @tap="prevDate">◀</text>
					<text class="arrow" @tap="nextDate">▶</text>
				</view>
			</view>
			
			<view class="calories-info">
				<view class="calories-chart">
					<view class="progress-ring">
						<text class="calories-value">{{ todaySummary.caloriesPercent }}%</text>
						<text class="calories-label">热量</text>
					</view>
				</view>
				<view class="calories-details">
					<view class="calories-item">
						<text class="item-value">{{ todaySummary.totalCalories }}千卡</text>
						<text class="item-label">已摄入</text>
					</view>
					<view class="calories-item">
						<text class="item-value">{{ todaySummary.goalCalories }}千卡</text>
						<text class="item-label">每日目标</text>
					</view>
				</view>
			</view>
			
			<view class="nutrients-info">
				<view class="nutrient-item">
					<view class="nutrient-progress" :style="{ width: todaySummary.carbsPercent + '%' }"></view>
					<text class="nutrient-label">碳水化合物</text>
					<text class="nutrient-value">{{ todaySummary.carbsValue }}g</text>
				</view>
				<view class="nutrient-item">
					<view class="nutrient-progress" :style="{ width: todaySummary.proteinPercent + '%' }"></view>
					<text class="nutrient-label">蛋白质</text>
					<text class="nutrient-value">{{ todaySummary.proteinValue }}g</text>
				</view>
				<view class="nutrient-item">
					<view class="nutrient-progress" :style="{ width: todaySummary.fatPercent + '%' }"></view>
					<text class="nutrient-label">脂肪</text>
					<text class="nutrient-value">{{ todaySummary.fatValue }}g</text>
				</view>
			</view>
		</view>
		
		<!-- 餐次列表 -->
		<view class="meal-list">
			<view class="meal-item" v-for="(meal, index) in mealTypes" :key="index" @tap="goToMealDetail(meal.type)">
				<view class="meal-icon">
					<image :src="meal.icon" mode="aspectFit"></image>
				</view>
				<view class="meal-info">
					<text class="meal-name">{{ meal.name }}</text>
					<text class="meal-summary">{{ getMealSummary(meal.type) }}</text>
				</view>
				<text class="meal-calories">{{ getMealCalories(meal.type) }}千卡</text>
				<text class="add-icon">+</text>
			</view>
		</view>
		
		<!-- 食物分类 -->
		<view class="section-header">
			<text class="section-title">食物库</text>
			<text class="section-more" @tap="goToFoodLibrary">更多</text>
		</view>
		<scroll-view class="food-categories" scroll-x="true" show-scrollbar="false">
			<view 
				class="category-item" 
				v-for="category in foodCategories" 
				:key="category.id"
				@tap="goToFoodList(category.id)"
			>
				<view class="category-icon">
					<image :src="category.icon" mode="aspectFit"></image>
				</view>
				<text class="category-name">{{ category.name }}</text>
			</view>
		</scroll-view>
		
		<!-- 推荐食谱 -->
		<view class="section-header">
			<text class="section-title">健康食谱</text>
			<text class="section-more" @tap="goToRecipes">更多</text>
		</view>
		<scroll-view class="recipe-list" scroll-x="true" show-scrollbar="false">
			<view 
				class="recipe-item" 
				v-for="recipe in recommendRecipes" 
				:key="recipe.id"
				@tap="goToRecipeDetail(recipe.id)"
			>
				<view class="recipe-image">
					<image :src="recipe.image || '/static/images/placeholder.png'" mode="aspectFill"></image>
				</view>
				<view class="recipe-info">
					<text class="recipe-name">{{ recipe.title }}</text>
					<text class="recipe-description">{{ recipe.description }}</text>
					<view class="recipe-nutrition">
						<text class="nutrition-item">{{ recipe.calories }}千卡</text>
						<text class="nutrition-item">碳水{{ recipe.carbs }}g</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { 
	getFoodCategories, 
	getRecommendRecipes, 
	getDietRecords, 
	getDietStats 
} from '@/common/api/diet.js';
import { getUserInfo } from '@/common/utils/auth.js';

// 状态变量
const foodCategories = ref([]);
const recommendRecipes = ref([]);
const selectedDate = ref(new Date());
const dietRecord = ref(null);
const dietStats = ref(null);

// 餐次定义
const mealTypes = ref([
	{ name: '早餐', type: 'breakfast', icon: '/static/images/breakfast.png' },
	{ name: '午餐', type: 'lunch', icon: '/static/images/lunch.png' },
	{ name: '晚餐', type: 'dinner', icon: '/static/images/dinner.png' },
	{ name: '加餐', type: 'snack', icon: '/static/images/snack.png' }
]);

// 今日饮食摘要计算
const todaySummary = computed(() => {
	// 默认值
	const defaultSummary = {
		totalCalories: 0,
		goalCalories: 2000,
		caloriesPercent: 0,
		carbsValue: 0,
		carbsPercent: 0,
		proteinValue: 0,
		proteinPercent: 0,
		fatValue: 0,
		fatPercent: 0
	};
	
	// 如果没有记录或统计数据，返回默认值
	if (!dietRecord.value) {
		return defaultSummary;
	}
	
	console.log('处理饮食记录数据:', JSON.stringify(dietRecord.value).substring(0, 200));
	
	// 获取总热量和营养素
	let totalCalories = 0;
	let totalCarbs = 0;
	let totalProtein = 0;
	let totalFat = 0;
	
	// 有两种可能的数据结构：1. 直接包含总值 2. 需要从meals数组计算
	if (typeof dietRecord.value.calories !== 'undefined') {
		// 直接使用记录中的值
		totalCalories = parseFloat(dietRecord.value.calories || 0);
		totalCarbs = parseFloat(dietRecord.value.carbohydrate || 0);
		totalProtein = parseFloat(dietRecord.value.protein || 0);
		totalFat = parseFloat(dietRecord.value.fat || 0);
	} else if (dietRecord.value.totalCalories) {
		// 使用totalXXX字段
		totalCalories = parseFloat(dietRecord.value.totalCalories || 0);
		totalCarbs = parseFloat(dietRecord.value.totalCarbs || dietRecord.value.totalCarbohydrate || 0);
		totalProtein = parseFloat(dietRecord.value.totalProtein || 0);
		totalFat = parseFloat(dietRecord.value.totalFat || 0);
	}
	
	// 如果有meals数组，计算总值
	if (Array.isArray(dietRecord.value.meals) && dietRecord.value.meals.length > 0) {
		console.log('从meals数组计算总营养素');
		// 累加所有餐次的营养素
		totalCalories = dietRecord.value.meals.reduce((sum, item) => sum + parseFloat(item.calories || 0), 0);
		totalCarbs = dietRecord.value.meals.reduce((sum, item) => sum + parseFloat(item.carbs || item.carbohydrate || 0), 0);
		totalProtein = dietRecord.value.meals.reduce((sum, item) => sum + parseFloat(item.protein || 0), 0);
		totalFat = dietRecord.value.meals.reduce((sum, item) => sum + parseFloat(item.fat || 0), 0);
	}
	
	// 格式化数字显示
	totalCalories = parseFloat(totalCalories).toFixed(0);
	totalCarbs = parseFloat(totalCarbs).toFixed(1);
	totalProtein = parseFloat(totalProtein).toFixed(1);
	totalFat = parseFloat(totalFat).toFixed(1);
	
	// 计算目标百分比
	const goalCalories = 2000; // 这里可以从用户配置中获取
	const caloriesPercent = Math.min(Math.round((totalCalories / goalCalories) * 100), 100);
	
	// 目标百分比（碳水:蛋白质:脂肪 = 50:30:20）
	const carbsGoal = goalCalories * 0.5 / 4; // 4卡/克
	const proteinGoal = goalCalories * 0.3 / 4; // 4卡/克
	const fatGoal = goalCalories * 0.2 / 9; // 9卡/克
	
	const carbsPercent = Math.min(Math.round((totalCarbs / carbsGoal) * 100), 100);
	const proteinPercent = Math.min(Math.round((totalProtein / proteinGoal) * 100), 100);
	const fatPercent = Math.min(Math.round((totalFat / fatGoal) * 100), 100);
	
	console.log('计算结果:', {
		totalCalories,
		goalCalories,
		caloriesPercent,
		carbsValue: totalCarbs,
		carbsPercent,
		proteinValue: totalProtein,
		proteinPercent,
		fatValue: totalFat,
		fatPercent
	});
	
	return {
		totalCalories,
		goalCalories,
		caloriesPercent,
		carbsValue: totalCarbs,
		carbsPercent,
		proteinValue: totalProtein,
		proteinPercent,
		fatValue: totalFat,
		fatPercent
	};
});

// 页面加载时初始化数据
onMounted(() => {
	loadFoodCategories();
	loadRecommendRecipes();
	loadDietRecord();
});

// 加载食物分类
const loadFoodCategories = async () => {
	try {
		const res = await getFoodCategories();
		if (res.code === 0) {
			foodCategories.value = res.data;
		}
	} catch (error) {
		console.error('加载食物分类失败', error);
	}
};

// 加载推荐食谱
const loadRecommendRecipes = async () => {
	try {
		const res = await getRecommendRecipes({ page: 1, pageSize: 5 });
		if (res.code === 0) {
			recommendRecipes.value = res.data.list;
		}
	} catch (error) {
		console.error('加载推荐食谱失败', error);
	}
};

// 加载饮食记录
const loadDietRecord = async () => {
	try {
		const formattedDate = formatDateForAPI(selectedDate.value);
		// 获取用户信息和用户ID
		const userInfo = getUserInfo();
		console.log('获取到的用户信息:', userInfo);
		
		// 使用userInfo中的id，如果不存在则使用默认值6
		const userId = userInfo && userInfo.id ? userInfo.id : 6;
		console.log('使用的用户ID:', userId, '日期:', formattedDate);
		
		// 构建请求参数
		const requestParams = {
			userId: userId,
			date: formattedDate
		};
		
		console.log('请求饮食记录参数:', requestParams);
		
		uni.showLoading({
			title: '加载中...'
		});
		
		const res = await getDietRecords(requestParams);
		
		console.log('饮食记录API响应:', JSON.stringify(res).substring(0, 500));
		
		uni.hideLoading();
		
		if (res.code === 0) {
			if (res.data) {
				dietRecord.value = res.data;
				
				// 确保各项数值存在
				if (typeof dietRecord.value.totalCalories === 'undefined') {
					dietRecord.value.totalCalories = 0;
				}
				if (typeof dietRecord.value.totalCarbs === 'undefined') {
					dietRecord.value.totalCarbs = 0;
				}
				if (typeof dietRecord.value.totalProtein === 'undefined') {
					dietRecord.value.totalProtein = 0;
				}
				if (typeof dietRecord.value.totalFat === 'undefined') {
					dietRecord.value.totalFat = 0;
				}
				if (!Array.isArray(dietRecord.value.meals)) {
					dietRecord.value.meals = [];
				}
				
				console.log('处理后的饮食记录:', dietRecord.value);
			} else {
				console.warn('API响应中无data字段:', JSON.stringify(res));
				
				// 如果没有记录，创建一个空记录
				dietRecord.value = {
					date: formattedDate,
					meals: [],
					totalCalories: 0,
					totalCarbs: 0,
					totalProtein: 0,
					totalFat: 0
				};
			}
		} else {
			console.warn('API返回错误:', JSON.stringify(res));
			
			// 如果没有记录，创建一个空记录
			dietRecord.value = {
				date: formattedDate,
				meals: [],
				totalCalories: 0,
				totalCarbs: 0,
				totalProtein: 0,
				totalFat: 0
			};
			
			// 显示API错误信息
			if (res.msg) {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				});
			}
		}
		
		// 加载统计数据
		loadDietStats();
	} catch (error) {
		console.error('加载饮食记录失败:', error);
		uni.hideLoading();
		
		// 如果没有记录，创建一个空记录
		dietRecord.value = {
			date: formatDateForAPI(selectedDate.value),
			meals: [],
			totalCalories: 0,
			totalCarbs: 0,
			totalProtein: 0,
			totalFat: 0
		};
		
		uni.showToast({
			title: '加载饮食记录失败',
			icon: 'none'
		});
	}
};

// 加载统计数据
const loadDietStats = async () => {
	try {
		// 获取30天的统计数据
		const endDate = formatDateForAPI(selectedDate.value);
		const startDate = formatDateForAPI(new Date(selectedDate.value.getTime() - 30 * 24 * 60 * 60 * 1000));
		const userId = getUserId();
		
		const res = await getDietStats({ 
			userId: userId,
			startDate: startDate,
			endDate: endDate 
		});
		
		if (res.code === 0) {
			dietStats.value = res.data;
		}
	} catch (error) {
		console.error('加载统计数据失败', error);
	}
};

// 前一天
const prevDate = () => {
	selectedDate.value = new Date(selectedDate.value.getTime() - 24 * 60 * 60 * 1000);
	loadDietRecord();
};

// 后一天
const nextDate = () => {
	const tomorrow = new Date(selectedDate.value.getTime() + 24 * 60 * 60 * 1000);
	// 不能选择未来的日期
	if (tomorrow <= new Date()) {
		selectedDate.value = tomorrow;
		loadDietRecord();
	}
};

// 获取指定餐次的热量总和
const getMealCalories = (mealType) => {
	if (!dietRecord.value) return 0;
	
	// 如果当前餐次类型与记录的mealType匹配，直接返回总热量
	if (dietRecord.value.mealType !== undefined && 
		(dietRecord.value.mealType === getMealTypeNumber(mealType) || 
		 dietRecord.value.mealType === mealType)) {
		return parseFloat(dietRecord.value.calories || 0).toFixed(0);
	}
	
	// 字符串类型的mealType和数字类型的mealType映射
	const mealTypeMap = {
		'breakfast': '0',
		'lunch': '1',
		'dinner': '2',
		'snack': '3'
	};
	
	// 从meals数组中过滤出指定餐次的记录
	if (Array.isArray(dietRecord.value.meals)) {
		const mealItems = dietRecord.value.meals.filter(item => {
			return item.mealType === mealType || 
				  item.mealType === mealTypeMap[mealType] ||
				  item.mealType === getMealTypeNumber(mealType).toString();
		});
		
		if (mealItems.length === 0) return 0;
		
		return mealItems.reduce((sum, item) => sum + parseFloat(item.calories || 0), 0).toFixed(0);
	}
	
	return 0;
};

// 获取指定餐次的食物摘要
const getMealSummary = (mealType) => {
	if (!dietRecord.value) return '未记录';
	
	// 如果当前餐次类型与记录的mealType匹配，直接返回食物名称
	if (dietRecord.value.mealType !== undefined && 
		(dietRecord.value.mealType === getMealTypeNumber(mealType) || 
		 dietRecord.value.mealType === mealType)) {
		return dietRecord.value.foodName || '未记录';
	}
	
	// 字符串类型的mealType和数字类型的mealType映射
	const mealTypeMap = {
		'breakfast': '0',
		'lunch': '1',
		'dinner': '2',
		'snack': '3'
	};
	
	// 从meals数组中过滤出指定餐次的记录
	if (Array.isArray(dietRecord.value.meals)) {
		const mealItems = dietRecord.value.meals.filter(item => {
			return item.mealType === mealType || 
				  item.mealType === mealTypeMap[mealType] ||
				  item.mealType === getMealTypeNumber(mealType).toString();
		});
		
		if (mealItems.length === 0) return '未记录';
		
		// 最多显示两个食物名称，如有更多则显示"等x种食物"
		if (mealItems.length === 1) {
			return mealItems[0].foodName || '未命名食物';
		} else {
			return `${mealItems[0].foodName}等${mealItems.length}种食物`;
		}
	}
	
	return '未记录';
};

// 将字符串餐次类型转换为数字
const getMealTypeNumber = (mealType) => {
	switch (mealType) {
		case 'breakfast': return 0;
		case 'lunch': return 1;
		case 'dinner': return 2;
		case 'snack': return 3;
		default: return -1;
	}
};

// 跳转到餐次详情页面
const goToMealDetail = (mealType) => {
	uni.navigateTo({
		url: `/pages/diet/meal?type=${mealType}&date=${formatDateForAPI(selectedDate.value)}`
	});
};

// 跳转到食物列表页面
const goToFoodList = (categoryId) => {
	uni.navigateTo({
		url: `/pages/diet/food-list?categoryId=${categoryId}`
	});
};

// 跳转到食物库页面
const goToFoodLibrary = () => {
	uni.navigateTo({
		url: '/pages/diet/food-library'
	});
};

// 跳转到食谱详情页面
const goToRecipeDetail = (recipeId) => {
	// 保存ID到全局变量
	getApp().globalData = getApp().globalData || {}
	getApp().globalData.recipeParams = {
		id: recipeId
	}
	console.log('跳转到食谱详情，ID:', recipeId)
	
	uni.navigateTo({
		url: `/pages/diet/recipe?id=${recipeId}`,
		fail: (err) => {
			console.error('跳转失败:', err)
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			})
		}
	});
};

// 跳转到食谱列表页面
const goToRecipes = () => {
	uni.navigateTo({
		url: '/pages/diet/recipes'
	});
};

// 格式化日期显示（年月日 星期几）
const formatDate = (date) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
	const weekDay = weekDays[date.getDay()];
	
	return `${year}年${month}月${day}日 星期${weekDay}`;
};

// 格式化日期为API所需格式（yyyy-MM-dd）
const formatDateForAPI = (date) => {
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	
	return `${year}-${month}-${day}`;
};

// 获取用户ID
const getUserId = () => {
	// 从auth.js中获取用户信息
	const userInfo = getUserInfo();
	// 如果有用户信息且有id，则返回id，否则返回默认值6
	return userInfo?.id || 6;
};
</script>

<style>
.diet-container {
	padding: 30rpx;
	min-height: 100vh;
	background-color: #f5f7fa;
}

.page-header {
	margin-bottom: 20rpx;
}

.title {
	font-size: 48rpx;
	font-weight: bold;
	color: #333;
}

.daily-summary {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.date-selector {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.date-label {
	font-size: 30rpx;
	color: #333;
	font-weight: 500;
}

.date-arrows {
	display: flex;
	align-items: center;
}

.arrow {
	font-size: 28rpx;
	color: #666;
	margin: 0 10rpx;
	padding: 5rpx 10rpx;
}

.calories-info {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.calories-chart {
	width: 160rpx;
	height: 160rpx;
	margin-right: 20rpx;
}

.progress-ring {
	width: 100%;
	height: 100%;
	border-radius: 50%;
	background-color: #f0f8ff;
	border: 10rpx solid #4caf50;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.calories-value {
	font-size: 36rpx;
	font-weight: bold;
	color: #4caf50;
}

.calories-label {
	font-size: 24rpx;
	color: #666;
}

.calories-details {
	flex: 1;
}

.calories-item {
	margin-bottom: 10rpx;
}

.item-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.item-label {
	font-size: 26rpx;
	color: #666;
	margin-left: 10rpx;
}

.nutrients-info {
	margin-top: 10rpx;
}

.nutrient-item {
	position: relative;
	height: 50rpx;
	background-color: #f5f5f5;
	border-radius: 25rpx;
	margin-bottom: 15rpx;
	overflow: hidden;
	display: flex;
	align-items: center;
	padding: 0 20rpx;
}

.nutrient-progress {
	position: absolute;
	left: 0;
	top: 0;
	height: 100%;
	background-color: #4caf50;
	opacity: 0.3;
	border-radius: 25rpx;
}

.nutrient-label {
	font-size: 26rpx;
	color: #333;
	z-index: 1;
}

.nutrient-value {
	font-size: 26rpx;
	color: #333;
	font-weight: bold;
	margin-left: auto;
	z-index: 1;
}

.meal-list {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 10rpx 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.meal-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.meal-item:last-child {
	border-bottom: none;
}

.meal-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 40rpx;
	overflow: hidden;
	margin-right: 20rpx;
}

.meal-icon image {
	width: 100%;
	height: 100%;
}

.meal-info {
	flex: 1;
}

.meal-name {
	font-size: 30rpx;
	color: #333;
	font-weight: 500;
}

.meal-summary {
	font-size: 24rpx;
	color: #999;
	margin-top: 5rpx;
}

.meal-calories {
	font-size: 28rpx;
	color: #666;
	margin-right: 20rpx;
}

.add-icon {
	font-size: 36rpx;
	color: #4caf50;
	font-weight: bold;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 30rpx 0 20rpx;
}

.section-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.section-more {
	font-size: 26rpx;
	color: #666;
}

.food-categories {
	white-space: nowrap;
	margin-bottom: 30rpx;
}

.category-item {
	display: inline-block;
	width: 150rpx;
	text-align: center;
	margin-right: 20rpx;
}

.category-icon {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: #fff;
	margin: 0 auto 10rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.category-icon image {
	width: 60%;
	height: 60%;
}

.category-name {
	font-size: 26rpx;
	color: #333;
}

.recipe-list {
	white-space: nowrap;
}

.recipe-item {
	display: inline-block;
	width: 500rpx;
	background-color: #fff;
	border-radius: 16rpx;
	overflow: hidden;
	margin-right: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.recipe-image {
	width: 100%;
	height: 250rpx;
}

.recipe-image image {
	width: 100%;
	height: 100%;
}

.recipe-info {
	padding: 15rpx;
}

.recipe-name {
	font-size: 30rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 5rpx;
}

.recipe-description {
	font-size: 24rpx;
	color: #666;
	white-space: normal;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 10rpx;
	height: 70rpx;
}

.recipe-nutrition {
	display: flex;
}

.nutrition-item {
	font-size: 22rpx;
	color: #999;
	margin-right: 15rpx;
}
</style> 